<link rel="stylesheet" href="${ctx}/imStatic/css/contextMenu.css">
<link rel="stylesheet" href="${ctx}/imStatic/css/imStyle.css">
<script src="${ctx}/imStatic/js/util.js"></script>
<script src="${ctx}/imStatic/js/message.js"></script>
<script src="${ctx}/imStatic/js/messagebody.js"></script>
<script src="${ctx}/imStatic/js/websocketconfig.js"></script>

<!-- 页面唯一标识统一用id='ccpimcont-自定义名字'  class在定义时,注意模块页面之间不重复-->

<!--面板功能选择-->
<div id="ccpimcont-imfunctions" style="display: none;">
    <ul class="imfunctionstyle">
        <li ccpim-event="userinfos">用户信息</li>
    </ul>
</div>

<!--群组功能扩展-->
<div id="ccpimcont-groupfunctions" style="display: none;">
    <ul class="groupfunctionstyle">
        <li ccpim-event="creatGroup">新建群聊</li>
    </ul>
</div>

<!--新建群聊 -->
<div id="ccpimcont-creatGroups" style="display: none">
    <div class="leftSelect" style="margin: 10px 0 0 10px;float: left">
        <input type="text" class="mainPanelSelectPen">
        <ul id="mainPanelSelect" class="ztree" style="height: 310px;width:240px;overflow: auto"></ul>
    </div>
    <div class="rightSelect" style="float: left;margin-top: 35px;margin-left: 6px">
        <ul class="groupPersonnels" style="height: 310px;width:240px;overflow: auto;"></ul>
    </div>
</div>

<style>

</style>
<script>
    var currentUserId = '${currentUserId}';
    var multipartMaxSize = '${multipartMaxSize}';
    var singleChat = '1';
    var groupChat = '2';
    var singleChatClear = '3';
    var onlineStatus;
    var __ctx = '${ctx}';
    layui.config({
        base: serverPath.imPath + staticPath.imPath
    }).extend({
        imindex: 'imindex'
        ,contextMenu:'js/contextMenu'
    });
    layui.use(['layim','imindex'], function(){
        var $=layui.jquery,layim = layui.layim,imindex=layui.imindex;
        var sendMsg=function(msg,receiver,group){
            var message = new proto.Model();
            var content = new proto.MessageBody();
            message.setMsgtype(4);
            message.setCmd(5);
            message.setGroupid(group);//群ID
            message.setToken(currentUserId);
            message.setSender(currentUserId);//发件人
            message.setReceiver(receiver);//好友ID
            content.setContent(msg);
            content.setType(0);
            message.setContent(content.serializeBinary());
            socket.send(message.serializeBinary());
        };
        //基础配置
        layim.config({

            //初始化接口
            init: {
                url: __ctx+'/im/mainPanelInit'
            }

            //查看群员接口
            ,members: {
                url:  __ctx+"/im/imRoomUser/list"
                ,data: {}
            }

            //上传图片接口
            ,uploadImage: {
                url:  __ctx+'/im/fileUpload' //（返回的数据格式见下文）
                ,type: 'post' //默认post
               ,size:51200 //文件大小限制   0表示不限制
            }

            //上传文件接口
            ,uploadFile: {
                url:  __ctx+'/im/fileUpload' //（返回的数据格式见下文）
                ,type: 'post' //默认post
                ,size:multipartMaxSize  //文件大小限制   0表示不限制
            }

            ,isAudio: false //开启聊天工具栏音频
            ,isVideo: false //开启聊天工具栏视频

            //扩展工具栏
            ,tool: []

            //,brief: true //是否简约模式（若开启则不显示主面板）

            ,title: '消息面板' //自定义主面板最小化时的标题
            //,right: '100px' //主面板相对浏览器右侧距离
            //,minRight: '90px' //聊天面板最小化时相对浏览器右侧距离
            ,initSkin: '2.jpg' //1-5 设置初始背景
            //,skin: ['aaa.jpg'] //新增皮肤
            //,isfriend: false //是否开启好友
            //,isgroup: false //是否开启群组
            //,min: true //是否始终最小化主面板，默认false
            ,notice: false //是否开启桌面消息提醒，默认false
            //,voice: false //声音提醒，默认开启，声音文件为：default.mp3

             ,msgbox:  __ctx+'/im/imSystemMessage/view/list' //消息盒子页面地址，若不开启，剔除该项即可
            // ,find: layui.cache.dir + 'css/modules/layim/html/find.html' //发现页面地址，若不开启，剔除该项即可
            ,chatLog:  __ctx+'/im/view/chatLog' //聊天记录页面地址，若不开启，剔除该项即可

        });
        //监听在线状态的切换事件
        layim.on('online', function(data){
            if(onlineStatus && onlineStatus == data ){
                return;
            }
            onlineStatus = data;
            var message = new proto.Model();
            if(data == 'online'){
                message.setCmd(3);
            }else{
                message.setCmd(4);
            }
                message.setMsgtype(4);
                socket.send(message.serializeBinary());
        });

        //监听签名修改
        layim.on('sign', function(value){
             $.ajax({
                url:  __ctx+"/im/imUser/updateSign",
                method: "get",
                contentType: 'application/json',
                dataType: 'json',
                data:{sign:value},
                success: function (result) {
                    if (result.code === 0) {
                    } else {
                        layer.alert(result.msg);
                    }
                }
             });
             return false;
        });

        //监听layim建立就绪
        layim.on('ready', function(res){
            //更新右键点击事件
            imindex.contextMenuconfig();
            //取得离线消息
            showOfflineMsg();
            //消息盒子
            if(res.mine.msgNum && res.mine.msgNum > 0){
                layui.imindex.msgboxIndex=res.mine.msgNum;
                layim.msgbox(res.mine.msgNum);
            }
            //个性签名  增加内容提示效果
            var imremarkIndex='';//个性签名弹窗名称记录
            $(".layui-layim-info .layui-layim-remark").hover(function(){
                var html=$(this).val();
                html='个性签名更新: '+html;
                imremarkIndex=layer.tips(html, this, {
                    tips: 3
                    ,time: 0
                    ,anim: 5
                    ,fixed: true
                    ,skin: 'layui-box layui-layim-contextmenu ccpim-imremark'
                    ,success: function(layero){
                        var stopmp = function(e){ layui.stope(e); };
                        layero.off('mousedown', stopmp).on('mousedown', stopmp);
                    }
                });
                function hide(){
                    layer.close(imremarkIndex);
                }
                $(document).off('mousedown', hide).on('mousedown', hide);
                $(window).off('resize', hide).on('resize', hide);
            },function(){
                layer.close(imremarkIndex);
            });
        });

        //监听发送消息
        layim.on('sendMessage', function(data){
            var To = data.to;
            var my = data.mine;
            var message = my.content;
            var receiver =To.id+"";
            if(!currentUserId){
                return;
            }
            if(!message){
                layer.msg("请输入要发送的消息!");
                return;
            }
            if (socket.readyState == WebSocket.OPEN) {
                //判断是发送好友消息还是群消息
                if(To.type=="friend"){
                    sendMsg(message,receiver,null)
                }else{
                    if($(".layim-list-group li.layim-group"+receiver).length>0){
                        sendMsg(message,null,receiver)
                    }else{
                        layim.getMessage({
                            system: true
                            ,id: receiver
                            ,type: "group"
                            ,content: '此群已被群主解散或您已被移出群聊！'
                        });
                    }
                }
            }
        });

        //监听聊天窗口的切换
        layim.on('chatChange', function(res){
            var type = res.data.type;
            var id = res.data.id;
            if(type === 'friend'){
                modifyReadStatus(singleChatClear,id);
            } else if(type === 'group'){
                modifyReadStatus(groupChat,id);
            }
        });

        //当前收到消息发件人窗口是否打开选中
        var curFriendChatIsOpen = function(friendId){
            var currentChat =  layim.thisChat();
            if(!currentChat){
                return false;
            }
            var data = currentChat.data;
            var dataFriendId = data.id;
            if(!dataFriendId){
                return false;
            }
            if(friendId == dataFriendId){
                return true;
            }
        };

        //根据消息类型修改消息状态  0单  1群 3单 清所有
        var modifyReadStatus = function(type,id){
            $.ajax({
                type : "get",
                url :  __ctx+"/im/modifyReadStatus",
                dataType : "json",
                data:{"type":type , "id":id},
                success : function(result) {
                    if (result.code === 0) {
                    } else {
                        layer.alert(result.msg);
                    }
                }
            });
        };

        //拉取离线消息
        var showOfflineMsg = function (){
            $.ajax({
                type : "post",
                url :  __ctx+"/im/getOfflineMsg",
                dataType : "json",
                success : function(ret){
                   var data = ret.data;
                   var friendMsg = data.friendMsg;
                   var groupMsg = data.groupMsg;
                   var fromId = '';
                   var userData = '';
                   var userName = '';
                   var avatar = '';
                   var friendMsgId = [],groupId = [];
                    if(groupMsg&&groupMsg.length>0){
                        for(var i =0;i<groupMsg.length;i++){
                            fromId = groupMsg[i].fromId;
                            userName = groupMsg[i].username;
                            avatar = groupMsg[i].avatar;
                            layim.getMessage({
                                username: userName
                                ,avatar: avatar
                                ,id: groupMsg[i].toRoom
                                ,type: "group"
                                ,content: groupMsg[i].content
                                ,timestamp: groupMsg[i].sendTime
                                ,fromid: fromId
                                ,cid: groupMsg[i].id
                            });
                            if(curFriendChatIsOpen(groupMsg[i].toRoom)&&groupId.length==0){
                                groupId.push(groupMsg[i].toRoom);
                            }
                        }
                        if(groupId.length>0){
                            modifyReadStatus(groupChat,groupId);
                        }
                    }
                    if(friendMsg&&friendMsg.length>0){
                        for(var j =0;j<friendMsg.length;j++){
                            fromId = friendMsg[j].fromId;
                            userName = friendMsg[j].username;
                            avatar = friendMsg[j].avatar;
                            layim.getMessage({
                                 username: userName
                                ,avatar: avatar
                                ,id: fromId
                                ,type: "friend"
                                ,content: friendMsg[j].content
                                ,timestamp: friendMsg[j].sendTime
                                ,fromid: fromId
                                ,cid: friendMsg[j].id
                            });
                            if(curFriendChatIsOpen(fromId)){
                                friendMsgId.push(friendMsg[j].id);
                            }
                        }
                        if(friendMsgId.length>1){
                            modifyReadStatus(singleChat,friendMsgId.join(","));
                        }else if(friendMsgId.length>0){
                            modifyReadStatus(singleChat,friendMsgId);
                        }
                    }
                }
            });
        };

/*        var getUserData = function(sender){
            var data = {};
            var cache = layui.layim.cache();
            var username = "",avatar="",flag=false;
            if(sender){
                layui.each(cache.friend, function(index1, item1){
                    layui.each(item1.list, function(index, item){
                        if(item.id == sender){
                            username = item.username;
                            avatar = item.avatar;
                            return flag = true;
                        }
                    });
                    if(flag) return true;
                });
            }
            data['username'] = username;
            data['avatar'] = avatar;
            return data;
        };*/

        var initEventHandle = function () {
            //收到消息后
            socket.onmessage = function(event) {
                if (event.data instanceof ArrayBuffer){
                    var msg =  proto.Model.deserializeBinary(event.data);      //如果后端发送的是二进制帧（protobuf）会收到前面定义的类型
                    var msgCon =  proto.MessageBody.deserializeBinary(msg.getContent());
                    var cmd = msg.getCmd();
                    var sender = msg.getSender();
                    //心跳消息
                    if(cmd==2){
                        //发送心跳回应
                        var message = new proto.Model();
                        message.setCmd(2);
                        message.setMsgtype(4);
                        socket.send(message.serializeBinary());
                    }else if(cmd==3){
                        //上线
                        if(sender!=currentUserId){
                           //layer.msg(userData.username+"上线了！");
                            layim.setFriendStatus(msg.getSender(), 'online');
                        }
                    }else if(cmd==4){
                        //下线
                        if(sender!=currentUserId){
                            //layer.msg(userData.username+"已下线！");
                            layim.setFriendStatus(msg.getSender(), 'offline');
                        }
                    }else if(cmd==7){
                        var systemMsgType = msg.getMsgtype();
                        var systemSign = msg.getSign();
                        if(systemMsgType==99){
                            top.location.reload();
                        }else if(systemMsgType==0){
                            var model = eval("("+systemSign+")");
                            var has;
                            var cachedata= layui.layim.cache();
                            if(cachedata.group&&cachedata.group.length>0){
                                layui.each(cachedata.group, function(index, item){
                                    if(item.id==model.id ){
                                        return has = true
                                    }
                                });
                            }
                            if(!has){
                                layui.imindex.msgboxIndex=layui.imindex.msgboxIndex+1;
                                layim.addList({
                                    type: 'group' //列表类型，只支持friend和group两种
                                    ,avatar: model.avatar //群组头像
                                    ,groupname: model.roomName //群组名称
                                    ,id: model.id //群组id
                                });
                            }
                            layim.getMessage({
                                system: true
                                ,id: model.id
                                ,type: "group"
                                ,content:model.addUserContent
                            });
                            imindex.contextMenuconfig();
                            //加入了某个群
                        }else if(systemMsgType==1){
                            layui.imindex.msgboxIndex=layui.imindex.msgboxIndex+1;
                            //被踢了群组
                            layim.getMessage({
                                system: true
                                ,id: systemSign
                                ,type: "group"
                                ,content: '您已被移除该群'
                            });
                            imindex.removegroupfriend({
                                type:'group'
                               ,id: systemSign
                            })
                        }else if(systemMsgType==4){
                            var modelgrouponfo = eval("("+systemSign+")");
                            imindex.events.synchgroupInfor({
                                id:modelgrouponfo.id    //群组id
                                ,name: modelgrouponfo.roomName   //群组名称
                                ,avatar:modelgrouponfo.avatar   //群组头像
                            })
                        }else if(systemMsgType==5){
                            layui.imindex.msgboxIndex=layui.imindex.msgboxIndex+1;
                            //解散了群组
                            layim.getMessage({
                                system: true
                                ,id: systemSign
                                ,type: "group"
                                ,content: '该群已解散'
                            });
                            imindex.removegroupfriend({
                                type:'group'
                                ,id: systemSign
                            })
                        }else if(systemMsgType==6){
                            //修改了用户信息
                            var modeluserinfo = eval("("+systemSign+")");
                            imindex.events.synchuserInfor({
                                id:modeluserinfo.id    //群组id
                                ,username: modeluserinfo.username   //用户名称
                                ,avatar:modeluserinfo.avatar   //用户头像
                                ,sign:modeluserinfo.sign   //用户签名
                            })
                        }else{
                            //其他系统消息....
                        }
                        if(layui.imindex.msgboxIndex>0){
                            layim.msgbox(layui.imindex.msgboxIndex);//消息提醒
                        }
                    } else{
                        //显示非自身消息
                        if(sender!=currentUserId){
                            //不显示用户组消息
                            var avatar = msg.getToken()?__ctx+msg.getToken():'';
                            var username = msg.getSign();
                            var time = (new Date(msg.getTimestamp())).getTime();
                            var msgId = msg.getMsgid();
                            if(msg.getGroupid()==null||msg.getGroupid().length<1){
                                layim.getMessage({
                                    username: username
                                    ,avatar: avatar
                                    ,id: sender
                                    ,type: "friend"
                                    ,content: msgCon.getContent()
                                    ,timestamp: time
                                    ,fromid: sender
                                    ,cid: msgId
                                });
                                //开启并选中着窗口
                                if(curFriendChatIsOpen(sender)){
                                    modifyReadStatus(singleChat,msgId);
                                }
                            }else{
                                var groupId = msg.getGroupid();
                                layim.getMessage({
                                    username: username
                                    ,avatar: avatar
                                    ,id: groupId
                                    ,type: "group"
                                    ,content: msgCon.getContent()
                                    ,timestamp: time
                                    ,fromid: sender
                                    ,cid: msgId
                                });
                                //开启并选中着窗口
                                if(curFriendChatIsOpen(groupId)){
                                    modifyReadStatus(groupChat,groupId);
                                }
                            }
                        }
                    }
                }else {
                    var data = event.data;                //后端返回的是文本帧时触发
                }
            };
            //连接后
            socket.onopen = function(event) {
                var message = new proto.Model();
                var browser=BrowserUtil.info();
                message.setVersion("1.0");
                message.setDeviceid("");
                message.setCmd(1);
                message.setSender(currentUserId);
                message.setMsgtype(1);
                message.setFlag(1);
                message.setPlatform(browser.name);
                message.setPlatformversion(browser.version);
                message.setToken(currentUserId);
                var bytes = message.serializeBinary();
                socket.send(bytes);
                layim.setFriendStatus(currentUserId, 'online');
            };
            //连接关闭
            socket.onclose = function(event) {
                layim.setFriendStatus(currentUserId, 'offline');
                layer.confirm('您已下线，重新上线?', function(index){
                    reconnect(websocketurl,initEventHandle);
                    layer.close(index);
                });
            };
            //连接出错
            socket.onerror = function () {
                reconnect(websocketurl,initEventHandle);
            };
        };
        //创建连接
        createWebSocket(websocketurl,initEventHandle);
    });
</script>


